define(['moment', 'module/moduleMobile/program/mobile01/CheckIn.service',
'module/moduleMobile/program/mobile01/CheckOut.service',
'module/moduleMobile/program/mobile01/MaterialSetUp.service',
'module/moduleMobile/program/mobile01/judgeSpc.service'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', 'config', '$CheckInService', '$CheckOutService', '$MaterialSetUp','$judgeSpcService', '$document', '$timeout',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, config, $CheckInService, $CheckOutService, $MaterialSetUp, $judgeSpcService, $document, $timeout) {
            // 20230314 modify by Alan for#130236 : 引入$timeout
            $scope.init = function(){
                // 20230303 modify by Alan for#: module_setting卡控
                $scope.MTL_OPB = config.cache.module_setting.MTL_OPB;
                $scope.user_name = config.cache.name;
                $scope.shift_info = config.cache.shift_info;
                $scope.mode = 'R';
                $scope.onwork_time = config.cache.onwork_time;
                $scope.machines_length = $stateParams.data.machines_length;
                $scope.badreason_searchShow={reason_no:false};
                // 20221031 modify by Alan for#120992 : 移除載入時查詢所有批號
                $scope.status_list = [{name: $filter('translate')('mobile01.status_run'), value:'R'}, {name:$filter('translate')('mobile01.status_queue'), value: 'Q'}];
                getPermission();
                
                //  20221128 modify by shiwl : 通过配置中新增扫描加载生产任务选项判断是否加载
                let scanLoadReportingTask = JSON.parse(localStorage.getItem(config.appName + "_setting")).scanLoadReportingTask ;
                if(scanLoadReportingTask=='Y'){
                        return false;
                } else {
                        machine_working_info_get($stateParams.data.machine_no, function(){});
                }
            };

            // 判斷按鈕權限
            function getPermission() {
                $scope.permission = {
                    B0204: true, // 上料
                    B0220: true, // 下料
                    B0501: true, // 首檢
                    B0230: true, // 標籤列印
                    B0205: true, // 進站
                    B0206: true  // 出站
                };

                if(config.cache.permissions && config.cache.permissions.length > 0){
                    for(permission in $scope.permission){
                        if(config.cache.permissions.indexOf(permission) === -1){
                            $scope.permission[permission] = false;
                        }
                    }
                }  
            }

            $scope.back = function(){
                // 20230215 modify by Alan for M#126937:  修正iOS返回時卡死
                $scope.items = null;
                $timeout(() => $rootScope.changeProgram('home', true))
            };

            $scope.QRCodeScanner = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        input_plot_no_callback(result.text);
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation : 'portrait'
                });
            };

            var element_plot_no = document.getElementById('input_plot');
            //barcode輸入
            $scope.input_plot_no = function(barcode){
                input_plot_no_callback(barcode);
            };

            $scope.materialSetDown = function(){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_MAT.system_command_set_process',
                    content: {
                        key_no:$stateParams.data.machine_no,
                        command:'001'
                    },
                    success: function (data) {
                        $rootScope.showToast($filter('translate')('mobile01.msg.material_set_down_success'));
                        // 20221031 modify by Alan for#120992 : 改用新的服務
                        machine_working_info_get($stateParams.data.machine_no);
                    }
                });
            };

            $scope.materialSetUp = function(item){
                $MaterialSetUp.init({
                    machine_no:$stateParams.data.machine_no,
                    item : item,
                    callback:function(){
                        // 20221031 modify by Alan for#120992 : 改用新的服務
                        machine_working_info_get($stateParams.data.machine_no);
                    }
                });
            };

            $scope.tagPrinter = function(item){
                $mdDialog.serviceDialog('mobile14Service', {plotItem:item});
            }

            // 20200305 modify by WeiTing for M#66737 - 增加電腦版 SPC檢驗。 -- start

            function opqcreason_info_get(item, feedback){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.op_qcreason_info_get',
                    content: {
                        op_no: item.op_no,
                        lot_no: item.plot_no,
                        machine_no: '',
                        area_no: '',
                        type: '0'
                    },
                    success: function (data) {
                        if(feedback)
                            feedback(data);
                    }
                });
            };

            function judgeSpcProcess(item, area, feedback){
                var content = {
                    op_no: item.op_no,
                    plot_no: item.plot_no,
                    employee_no: config.cache.account,
                    area_no: area.area_no,
                    machine_no: $stateParams.data.machine_no,
                    check_qty: 1, // 預設檢驗數量是 1，當 SPC檢驗時，可以更改檢驗數量。
                    check_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                    productid: item.item_name,
                    qc_result: 'Y',
                    qc_type: '0', //首檢qc_type=0, 巡檢qc_type=1
                    qc_reason_detail:[],
                    run_type: 0 // run_type=0：一開始判斷要走SPC還是標準版帶 0 ; run_type=1：SPC檢驗和標準版檢驗送回資料帶 1。
                };

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.first_piece_check_process',
                    content: content,
                    success: function (data, response) {
                        if(feedback)
                            feedback(data, response);
                    }
                });
            };



            $scope.firstPieceCheck = function(item){
                opqcreason_info_get(item, function(area){
                    judgeSpcProcess(item, area, function(data){
                        if(data.run_spc == 1){
                            // 如果 run_spc 是 1 就走 SPC開窗檢驗
                            $judgeSpcService.init({
                                machine_no: $stateParams.data.machine_no,
                                inspectionInfo : item,
                                area_no: area.area_no
                            });
                        } else {
                            $rootScope.changeProgram('mobile03', {
                                data:{
                                    parent: 'mobile01',
                                    type: 0,
                                    machines_length: $scope.machines_length,
                                    op_no: item.op_no,
                                    op_name: item.op_name,
                                    machine_no: $stateParams.data.machine_no,
                                    plot_no: item.plot_no,
                                    product_id:item.item_name,
                                }
                            });
                        };
                    });
                });
            };
            // 20200305 modify by WeiTing for M#66737 - 增加電腦版 SPC檢驗。 -- end

            $scope.changeTab = function(tab_index){
                $scope.status_list.forEach(function(data, index){
                    if(index == tab_index){
                        data.select = true;
                    } else {
                        data.select = false;
                    }
                });
                // 20200309 modify by WeiTing for M#65990 - 現在掃描生產批，如果沒有符合的話，會把輸入的值變成過濾條件，所以重新點擊 Tab時，要清空過濾條件。
                $scope.barcode_plot_no_filter = '';
            };

            $scope.getTabSize = function(status){
                var list = [];
                if($scope.items && $scope.items.length > 0){
                    $scope.items.forEach(function(item){
                        if(item.status == status){
                            list.push(item);
                        }
                    });
                }
                return list.length;
            };

            $scope.checkin = function(item){
                getPlotInfo($stateParams.data.machine_no, item, '1', function(item){
                    $CheckInService.init({
                        machine_no:$stateParams.data.machine_no,
                        item : item,
                        callback:function(){
                            // 20221031 modify by Alan for#120992 : 改用新的服務
                            machine_working_info_get($stateParams.data.machine_no);
                        }
                    });
                });
            };

            $scope.checkout = function(item){
                var msg = '';
                //20190422 modify by Dustdusk for M#56727: 根據AllowCheckOutWithOutOperator判斷出站是否需要有人在線上並跳出確認框進行上工
                //20211125 modify by Liuyang for M#99947:改为Y或1时检核
                if(config.cache.sys_parameter.AllowCheckOutWithOutOperator == 'Y' || config.cache.sys_parameter.AllowCheckOutWithOutOperator == '1'){
                    if($stateParams.data.employee_status == 'U'){
                        msg = $filter('translate')('mobile01.msg.no_online_operator_reworkon');
                    }
                }
                if(msg == ''){
                    getPlotInfo($stateParams.data.machine_no, item, '2', function(item){
                        $CheckOutService.init({
                            machine_no:$stateParams.data.machine_no,
                            item : item,
                            callback:function(){
                                // 20221031 modify by Alan for#120992 : 改用新的服務
                                machine_working_info_get($stateParams.data.machine_no);
                            }
                        });
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('mobile01.checkin.msg.no_one_onwork'));
                }
            };

            //掃描條碼後選擇進出站
            function chooseCheckInOut(callback){
                var list = [
                    {code: 'Q', label: $filter('translate')('mobile01.check_in')},
                    {code: 'R', label: $filter('translate')('mobile01.check_out')}
                ];
                $rootScope.showSelect({
                    label: 'label',
                    code: 'code',
                    selectCode: '',
                    list: list,
                    confirm: function (item, dialog) {
                        dialog.hide();
                        if(callback)
                            callback(item.code);
                    }
                });
            }

            function input_plot_no_callback(barcode_plot_no){  
                //檢查輸入的對不對
                var temp_plot_array = barcode_plot_no.split(';');
                var plotItems = {'Q':[], 'R':[]};
                var plotItemList = [];
                $scope.items.forEach(function(production_info){
                    if(temp_plot_array.length == 2){
                        if(barcode_plot_no == (production_info.plot_no + ';' + production_info.op_no)){
                            if(!plotItems[production_info.status]){
                                plotItems[production_info.status] = [];
                            }
                            plotItems[production_info.status].push(production_info);
                            plotItemList.push(production_info);
                        }
                    } else {
                        if(barcode_plot_no == production_info.plot_no){
                            if(!plotItems[production_info.status]){
                                plotItems[production_info.status] = [];
                        }
                        plotItems[production_info.status].push(production_info);
                        plotItemList.push(production_info);
                    }
                };
               });
                if(Object.keys(plotItems).length == 0){
                        if(temp_plot_array.length == 2){
                        //刷入的生產批{{plot_no}}作業站{{op_no}}, 並不包含在本作業中，請確定刷入的條碼是否正確或確認選定的作業設備是否正確。
                        $scope.$root.showAlert($filter('translate')('mobile01.barcode.lotlog_opno_without_barcode', {plot_no:temp_plot_array[0], op_no:temp_plot_array[1]}));
                        } else {
                        //刷入的生產批{{plot_no}}, 並不包含在本作業中，請確定刷入的條碼是否正確或確認選定的作業設備是否正確。
                        $scope.$root.showAlert($filter('translate')('mobile01.barcode.lotlog_without_barcode', {plot_no:temp_plot_array[0]}));
                        };
                } else {
                if(plotItems['R'].length == 1 && plotItems['Q'].length == 1){
                    chooseCheckInOut(function(status){
                        var plotList = $filter('filter')(plotItemList, {status: status});
                        if(plotList.length > 0){
                            if(status == 'Q'){ //進站
                                $scope.changeTab(1);
                                $scope.checkin(plotList[0]);
                            } else { //出站
                                $scope.changeTab(0);
                                $scope.checkout(plotList[0]);
                            };
                        }
                  });
                } else if(plotItems['Q'].length == 1){
                        $scope.plotItem = plotItems['Q'][0];
                        //直接進站
                        $scope.changeTab(1);
                        $scope.checkin($scope.plotItem);
                } else if(plotItems['R'].length == 1){
                        $scope.plotItem = plotItems['R'][0];
                        $scope.changeTab(0);
                        $scope.checkout($scope.plotItem);
                }
                else {
                        // 20200309 modify by WeiTing for M#65990 - 現在掃描生產批，如果沒有符合的話，會把輸入的值變成過濾條件。
                  $scope.barcode_plot_no_filter = temp_plot_array[0];
               };   
                
               
            };
            };
            // 20221031 modify by Alan for#120992 : 將machine_working_info_get改為machine_working_info_"mobile"_get
            function machine_working_info_get(machine_no, feedback)  {
                var content = {
                    machine_no: machine_no,
                   // lot_no: $scope.lot_no,
                    data_type : '0001'
                };

                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_EQP.machine_working_info_get',
                    content : content,
                    success : function(data){
                        $scope.items = data.machine_production_info_detail; //今日生產任務
                        if(feedback)
                            feedback();
                    }
                });
            }

            function getPlotInfo(machine_no, plot, type, callback) {
                var content = {
                    machine_no : machine_no,
                    plot_no: plot.plot_no,
                    op_seq : '',//
                    op_no :plot.op_no,
                    workstation_no:'',//
                    qty: '',
                    return_type:type,
                };
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_WIP.plot_info_get',
                    content : content,
                    success : function(data){
                        //20181018 add by Dustdusk for M#: 增加機台點檢檢核功能
                        if(data.MsgLevel==0){
                            initPlotInfo(type, data, callback);
                        } else if(data.MsgLevel==1){
                            $rootScope.showConfirm(data.SysMsg, function(confirmDialog){
                                confirmDialog.hide();
                                initPlotInfo(type, data, callback);
                            });
                        } else if(data.MsgLevel==2){
                            $rootScope.showAlert(data.SysMsg);
                        }
                    }
                });
            }

            function initPlotInfo(type, data, callback){
                if(data.plot_info_get.length > 0){
                    // 20240205 modify by Alan for#156794 : 調整workstation_detail的結構與PC版一致
                    let plotInfo = data.plot_info_get[0];
                    if (plotInfo.workstation_detail.length > 0) {
                        if ((config.cache.sys_parameter.AllowCheckOutWithOutOperator == 'Y' || config.cache.sys_parameter.AllowCheckOutWithOutOperator == '1') && plotInfo.workstation_detail[0].labor_detail.length == 0) {
                            // 20230322 modify by Alan for#130407: 修正卡控提示
                            $rootScope.showAlert($filter('translate')('mobile01.checkout.msg.no_effect_work_time'));
                        } else {
                            plotInfo = angular.merge(plotInfo, plotInfo.workstation_detail[0]); // 保留給進站用
                            plotInfo.countMethod = data.CountMethod;
                            plotInfo.reworkMethod = data.auto_rework_material_process;
                            plotInfo.report_datetime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                            if(type=='1'){
                                plotInfo.qty = plotInfo.workstation_detail[0].check_in_qty;
                            } else if(type=='2'){
                                plotInfo.qty = plotInfo.good_qty = plotInfo.workstation_detail[0].check_out_qty;
                                plotInfo.total_abnormal_qty = 0;
                                plotInfo.total_surplus_qty = 0;
                                plotInfo.total_lack_qty = 0;

                                if (plotInfo.workstation_detail[0].abnormal_detail) {
                                    plotInfo.workstation_detail[0].abnormal_detail.forEach(function (abnormal_detail) {
                                        if(abnormal_detail.abnormal_type == '11'){
                                            plotInfo.total_surplus_qty  = (+plotInfo.total_surplus_qty) + (+abnormal_detail.defect_qty);
                                        } else {
                                            plotInfo.total_abnormal_qty = (+plotInfo.total_abnormal_qty) + (+abnormal_detail.defect_qty);
                                        }
                                    });
                                }
                                plotInfo.good_qty = (+plotInfo.good_qty) - (+plotInfo.total_abnormal_qty) + (+plotInfo.total_surplus_qty);

                                if(!plotInfo.machine_qty||plotInfo.machine_qty==''){
                                    plotInfo.machine_qty = 1;
                                }
                                for (var i = 0; i < plotInfo.workstation_detail[0].materials_detail.length; i++) {
                                    plotInfo.workstation_detail[0].materials_detail[i].use_qty = plotInfo.good_qty * plotInfo.workstation_detail[0].materials_detail[i].std_use_qty;
                                }
                                for (var i = 0; i < plotInfo.workstation_detail[0].labor_detail.length; i++) {
                                    plotInfo.workstation_detail[0].labor_detail[i].qty = plotInfo.qty;
                                }
                            }

                            callback(plotInfo);
                        }
                    } else {
                        $rootScope.showAlert('plot empty');
                    }
                } else {
                    $rootScope.showAlert('plot_info_get is empty');
                }
            }
        }
    ];
});
